import React, { useState, useEffect } from 'react'
import loginTitleIcon from '../assets/loginTitleIcon.png'
import { Button, Form, Input, Space, Typography, message } from 'antd'
import { CheckCircleFilled } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import MobileCopyright from '../components/MobileCopyright'
import Kefu from '../components/Kefu'
import MobileProductItem from '../components/MobileProductItem'
import MobileNavigator from '../components/MobileNavigator'
import MobileMyBanner from '../components/MobileBanner'
import MobileMyAvatar from '../components/MobileMyAvatar'
import MobileShoppingCart from '../components/MobileShoppingCart'
import { loginAPI, sendCodeAPI } from '../service/user'
import { setStorage, setToken } from '../utils/tools'

function MobileIndex() {
  // 路由跳转
  const navigate = useNavigate()
  const [disabled, setDisabled] = useState(false)
  const [countdown, setCountdown] = useState(60)
  const [timer, setTimer] = useState(null)
  const [checked, setChecked] = useState(false)
  const [phone, setPhone] = useState('')
  // 点击发送验证码
  const handleClick = async () => {
    // 获取用户输入的手机号码 如果手机号码格式 不正确，提示错误信息并返回
    if (!/^1[3456789]\d{9}$/.test(phone)) {
      message.error('请输入正确的手机号码')
      return
    }

    if (disabled) return // 如果按钮已禁用，则不执行任何操作

    // 发送验证码逻辑
    const res = await sendCodeAPI({ phone })
    console.log(res)
    if (res.status === 200) {
      // 将提示消息显示3秒钟
      message.success({
        content: '验证码发送成功',
        duration: 3 // 显示3秒
      })
    } else {
      message.error('发送失败：' + res.data.message)
      return false
    }

    // 设置按钮为禁用状态
    setDisabled(true)
    setCountdown(60) // 重置倒计时

    // 设置倒计时
    const interval = setInterval(() => {
      setCountdown((prevCountdown) => {
        if (prevCountdown === 0) {
          // 如果倒计时为0，清除定时器并重置按钮状态
          clearInterval(interval)
          setDisabled(false)
          return 60 // 重置倒计时状态
        }
        return prevCountdown - 1 // 否则递减倒计时
      })
    }, 1000)
    setTimer(interval)
  }
  // 登录逻辑
  const login = async (values) => {
    // 先接收许可协议
    if (!checked) {
      message.error('请先阅读并同意许可协议')
      return
    }
    const { phone, code } = values
    const res = await loginAPI({ phone, code })
    console.log(res)
    if (res.status === 200) {
      message.success('登录成功')
      setToken(res.data.data.authToken) // 保存token
      setStorage('username', res.data.data.username) // 保存用户名
      navigate('/home') // 登录成功，跳转到首页
    } else {
      message.error('登录失败，请检查手机号和验证码是否正确') // 登录失败，提示错误信息
    }
  }
  useEffect(() => {
    message.config({
      top: 300
    })
  }, [])
  useEffect(() => {
    return () => {
      if (timer) {
        clearInterval(timer) // 清除定时器
      }
    }
  }, [timer])
  return (
    <>
      {/* 顶部banner */}
      <MobileMyBanner />
      {/* 导航 */}
      <MobileNavigator />
      {/* 头像 */}
      <MobileMyAvatar />
      {/* 登录 */}
      <div className="mobileLoginWrap">
        <div className="loginTitle">
          <img src={loginTitleIcon} alt="" />
          <span>账号登录</span>
        </div>
        <div className="formWrap">
          <Form onFinish={login}>
            <Form.Item
              name="phone"
              rules={[
                { required: true, message: '请输入手机号' },
                // 验证手机号码格式
                { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号' }
              ]}
            >
              <Input
                placeholder="请输入手机号"
                // 保存手机号码
                onChange={(e) => setPhone(e.target.value)}
              />
            </Form.Item>
            <Form.Item>
              <Space.Compact
                style={{
                  width: '100%'
                }}
              >
                <Form.Item
                  name="code"
                  rules={[
                    { required: true, message: '请输入验证码' },
                    // 验证验证码格式
                    { pattern: /^\d{6}$/, message: '请输入6位验证码' }
                  ]}
                >
                  <Input placeholder="请输入验证码" />
                </Form.Item>
                <Button
                  style={{
                    backgroundColor: disabled ? 'gray' : '#333',
                    color: '#fff',
                    borderRadius: 0,
                    border: 'none',
                    width: '40%'
                  }}
                  disabled={disabled}
                  onClick={handleClick}
                >
                  {disabled ? `${countdown}s` : '发送验证码'}
                </Button>
              </Space.Compact>
            </Form.Item>
            <Form.Item style={{ marginBottom: '5vw', marginTop: '-6vw' }}>
              <Button
                htmlType="submit"
                block
                size="large"
                style={{
                  backgroundColor: '#d34145',
                  color: '#fff',
                  borderRadius: 0,
                  border: 'none'
                }}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
          <Typography.Paragraph
            style={{
              fontSize: 12,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}
            className="desc"
          >
            <span onClick={() => setChecked(!checked)}>
              {checked ? (
                <CheckCircleFilled
                  style={{ marginRight: 5, color: '#d34145', fontSize: 16 }}
                />
              ) : (
                <i
                  style={{
                    width: 15,
                    height: 15,
                    border: '2px solid #dedede',
                    borderRadius: '50%',
                    display: 'block',
                    marginRight: 5
                  }}
                ></i>
              )}
            </span>
            <span>
              我已阅读并同意<a href="#">《用户协议》</a>
              <a href="#">《隐私政策》</a> 
            </span>
          </Typography.Paragraph>
        </div>
      </div>
      {/* 请选择商品 */}
      <div className="mobileRightWrap">
        <div className="mobileRightContainer">
          <div className="mobileRightTitle">
            <span>请选择商品</span>
          </div>
          <div className="mobileRightContent">
            <div className="mobileRightActive">
              <span className="mobileDollarIcon">$</span>
              <span className="mobileText">特别活动</span>
            </div>
            <p className="mobileDescription">
              每个商品首次购买都可获得该商品额外0.5倍的加赠奖励。
              <br />
              在官网充值不影响游戏应用内商品的首充奖励次数。
            </p>

            {/* 商品列表 */}
            <div className="mobileProductList">
              <MobileProductItem />
              <MobileProductItem />
              <MobileProductItem />
            </div>
          </div>
        </div>
      </div>
      {/* 购物车 */}
      <MobileShoppingCart />
      {/* 版权 */}
      <MobileCopyright />
      <Kefu />
    </>
  )
}

export default MobileIndex
